<?php

namespace app\common\logic;

use think\Db;
use think\Model;

/**
 * 礼物逻辑类
 */
class GiftLogic extends Model
{
    protected $gift; //礼物模型
    protected $order; //订单模型
    protected $goods; //商品模型
    protected $user_id = 0; //用户id
    protected $pid = 0; //父id

    protected $order_sn;

    public function __construct()
    {
        parent::__construct();
        $this->gift = new \app\common\model\Gift();

    }


    /**
     * 设置用户id
     * @param $user_id
     */
    public function setUserId($user_id)
    {
        $this->user_id = $user_id;
    }

    /**
     * 设置父级id
     * @param $pid
     */
    public function setPid($pid)
    {
        $this->pid = $pid;
    }


    /**
     * 设置礼物模型
     * @param $gift
     */
    public function setGift($gift)
    {
        $this->gift = $gift;
    }

    /**
     * 设置订单模型
     * @param $order
     */
    public function setOrder($order)
    {
        $this->order = $order;
    }

    /**
     * 设置商品模型
     * @param $order
     */
    public function setGoods($goods)
    {
        $this->goods = $goods;
    }


    /**
     * 设置订单号
     * @param $order_sn
     */
    public function setOrderSn($order_sn)
    {
        $this->order_sn = $order_sn;
    }

    /**
     * 根据订单号获取礼物id
     * @param $order_sn
     */
    public function getGiftByOrderSn()
    {

        $giftM = new \app\common\model\Gift();
        $gift = [];

        $gift_ids = $this->getGiftIdsByOrderSn();
        if ($gift_ids['code'] == 0) {
            return $gift_ids;
        }

        foreach ($gift_ids['data'] as $k => $v) {
            $g = $giftM->get($v);
            $g->goods;
            $gift[$k] = $g->toArray();
        }


        return ['code' => 1, 'msg' => '', 'data' => $gift];
    }

    /**
     * 根据订单号 获取礼物id数组
     * @param $status
     * @param $is_same_order //是否是同一订单的礼物
     * @return array
     */
    public function getGiftIdsByOrderSn($status = '0,1', $is_same_order = 0)
    {
        $order_sn = $this->order_sn;
        //先查看一下 是不是 合并支付的主订单号
        $order_list = Db::name('order')->where("master_order_sn", $order_sn)->select();

        $gift_ids = [];
        if ($order_list) {
            foreach ($order_list as $key => $val) {
                if ($is_same_order == 1) {
                    $condition = ['order_id' => $val['id'], 'user_id' => $this->user_id,'order_sn' => $order_sn];
                } else {
                    $condition = ['order_id' => $val['id'], 'user_id' => $this->user_id, 'status' => ['in',$status], 'order_sn' => $order_sn];
                }

                $id = Db::name('gift')->where($condition)->value('id');
                if (!$id) {
//                    return ['code' => 0, 'msg' => '礼物不存在', 'data' => ''];
                } else {
                    array_push($gift_ids, $id);
                }
            }

        } else {
            $order_id = Db::name('order')->where(['order_sn' => $order_sn])->value('id');
            if (!$order_id) return ['code' => 0, 'msg' => '订单号不存在', 'data' => ''];

            if ($is_same_order == 1) {
                $condition = ['order_id' => $order_id, 'user_id' => $this->user_id, 'order_sn' => $order_sn];
            } else {
                $condition = ['order_id' => $order_id, 'user_id' => $this->user_id, 'status' => ['in',$status], 'order_sn' => $order_sn];
            }
            $id = Db::name('gift')->where($condition)->value('id');
            if (!$id) {

            } else {
                array_push($gift_ids, $id);
            }

        }

        if (empty($gift_ids)) {
            return ['code' => 0, 'msg' => '礼物已经抢完', 'data' => ''];
        }
        return ['code' => 1, 'msg' => '', 'data' => $gift_ids];

    }

    /**
     * 拆礼物
     * $gift_id 礼物id
     * $user_id 拆礼人id
     */
    public function addRobGift($user_id)
    {
        $gift_ids_result = $this->getGiftIdsByOrderSn('4', 0);

        if ($gift_ids_result['code'] == 0) {
            return $gift_ids_result;
        }

        $gift_ids = $gift_ids_result['data'];
        //是否能抢礼物
        $isCanRob = $this->canRobGift($user_id);
        if (!$isCanRob) {
            return ['code' => '0', 'msg' => '同一人送的礼只能抢一次', 'data' => ''];
        }

        //获取随机的一个礼物
        $gift_id = $gift_ids[array_rand($gift_ids)];

        $gift = \app\common\model\gift::get($gift_id);

        if ($gift['type'] == 1) {
            $ids = [];
            $pids = [];
            //送一人
            foreach ($gift_ids as $k => $v) {
                $giftone = \app\common\model\gift::get($v);

                if($giftone['user_id'] == $user_id){
                    return ['code' => 0, 'msg' => '自己不能拆自己的礼物哦!','data' => ''];
                }

                //如果有人领取过，则跳过
                if($giftone['status'] == 5){
                    return ['code' => 0, 'msg' => '手慢无哦, 下次快点哟！','data' => ''];
                    continue;
                }

                $data = [
                    'pid' => $giftone['id'],
                    'order_id' => $giftone['order_id'],
                    'goods_id' => $giftone['goods_id'],
                    'user_id' => $user_id,
                    'type' => $giftone['type'],
                    'price' => $giftone['price'],
                    'createtime' => time(),
                    'status' => '1',
                    'order_sn' => $giftone['order_sn']
                ];
                $newgift = \app\common\model\gift::create($data);
                $this->updateGiftStatus($v, 5);
                array_push($ids,$newgift->id);
                array_push($pids,$newgift->pid);
            }

            if ($newgift) {
                return ['code' => 1, 'msg' => '收礼成功', 'data' => ['pid' => $pids, 'id' => $ids,'type' => 1,'order_sn' => $giftone['order_sn']]];
            } else {
                return ['code' => 0, 'msg' => '收礼失败', 'data' => ''];
            }


        } else {
            //送多人

            if($gift['user_id'] == $user_id){
                return ['code' => 0, 'msg' => '自己不能拆自己的礼物哦!','data' => ''];
            }

            $data = [
                'pid' => $gift['id'],
                'order_id' => $gift['order_id'],
                'goods_id' => $gift['goods_id'],
                'user_id' => $user_id,
                'type' => $gift['type'],
                'price' => $gift['price'],
                'createtime' => time(),
                'status' => '1',
                'order_sn' => $gift['order_sn']

            ];
            $newgift = \app\common\model\gift::create($data);
            if ($newgift) {
                //设置状态为：好友已领取
//            Db::name('gift')->where('id',$gift['id'])->update(['status' => 5]);
                $this->updateGiftStatus($gift_id, 5);

                return ['code' => 1, 'msg' => '收礼成功', 'data' => ['pid' => $gift_id, 'id' => [$newgift->id],'type' => 2,'order_sn' => $gift['order_sn']]];
            } else {
                return ['code' => 0, 'msg' => '收礼失败', 'data' => ''];
            }

        }


    }

    public function getFollowUser()
    {
        $all = Db::name('gift')->where(['order_sn' => $this->order_sn])->count();

        $yiling = Db::name('gift')->where(['order_sn' => $this->order_sn, 'status' => '5'])->count();

        $giftIds = $this->getGiftIdsByOrderSn('5');

        $followUser = [];
        if ($giftIds['code'] == 1) {
            foreach ($giftIds['data'] as $k => $v) {
                $gift = \app\common\model\gift::get(['pid' => $v]);
                $gift->user;
                $gift->order;
                $gift->goods;

                $followUser[$k]['nickname'] = $gift->user['nickname'];
                $followUser[$k]['avatar'] = $gift->user['avatar'];
                $followUser[$k]['goods_price'] = $gift->order['goods_price'];
                $followUser[$k]['image'] = $gift->goods['image'];
            }
        }

        $data = [
            'total' => $all,
            'yiling' => $yiling,
            'followUser' => $followUser
        ];

        return $data;
    }

    /**
     * 是否能抢礼物
     * 拆礼物人
     * @param $user_id
     */
    public function canRobGift($user_id)
    {
        $gift_ids_result = $this->getGiftIdsByOrderSn('4,5', 0);

        if ($gift_ids_result['code'] == 0) {
            return $gift_ids_result;
        }

        $gift_ids = $gift_ids_result['data'];

        foreach ($gift_ids as $k => $v) {
            $count = Db::name('gift')->where(['user_id' => $user_id, 'pid' => $v])->count();
            if (intval($count) > 0) {
                return false;
            } else {
                continue;
            }
        }

        return true;

    }


    /**
     * 转赠抢礼物
     * @param $user_id //接收人id
     */
    public function zhuanzeng($user_id)
    {
        $gift = $this->gift;
        if ($this->gift['status'] == 1) {
            return ['code' => 0, 'msg' => '礼物还未分享', 'data' => ''];
        }
        if ($this->gift['status'] != 4) {
            return ['code' => 0, 'msg' => '该礼物已被抢光', 'data' => ''];
        }
        Db::name('gift')->where('id', $this->gift['id'])->update(['status' => '5']);

        $data = [
            'pid' => $gift['id'],
            'order_id' => $gift['order_id'],
            'goods_id' => $gift['goods_id'],
            'user_id' => $user_id,
            'type' => $gift['type'],
            'price' => $gift['price'],
            'createtime' => time(),
            'status' => '1'

        ];
        $newgift = \app\common\model\gift::create($data);

        if ($newgift) {
            $this->updateGiftStatus($this->gift['id'], 5);
            return ['code' => 1, 'msg' => '收礼成功', 'data' => ['pid' => $this->gift['id'], 'id' => $newgift->id]];
        } else {

            return ['code' => 0, 'msg' => '收礼失败', 'data' => ''];
        }
    }

//    /**
//     * 记录礼物领取进度
//     * @param $gift_id 礼物id
//     * @param $send_user_id 赠送人id
//     */
//    public function setGiftProgress($gift_id,$send_user_id){
//
//    }

//
//    /**
//     * 获取礼物领取进度
//     */
//    public function getProgressTextAttr($value,$data){
//
//    }

    /**
     * 修改礼物状态为朋友已领取， 原订单不显示
     * @param $gift_id
     * @param $status
     */
    public function updateGiftStatus($gift_id, $status)
    {
        Db::name('gift')->where('id', $gift_id)->update(['status' => $status]);
        $order_id = Db::name('gift')->where('id',$gift_id)->value('order_id');
        Db::name('order')->where(['id' => $order_id])->update(['deleted' => 1]);
    }


}